# Replication Script For Figures and Tables in
# Pinckney and Trilling
# "Breaking Down Pillars of Support for Democratic Backsliding"
# Analysis run in R version 4.4.1


# Set working directory to current directory

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

# Set-up packages and load data ####

library(tidyverse) # v. 2.0.0
library(marginaleffects) # v 0.23.0
library(modelsummary) # v. 2.2.0
library(sandwich) # v. 3.1-1
library(lmtest) # v. 0.9-40
library(texreg) # v.1.39.4

analysis.data <- read_rds("data/analysis-datasets.rds")

spell.level.data <- analysis.data[[1]]
tactic.level.data <- analysis.data[[2]]
loyalty.shift.data <- analysis.data[[3]]

# Set theme colors

theme.blue <- "#003C7F"
theme.green <- "#47A035"

# How Common and Successful is Civil Resistance During Democratic Backsliding? ####

sum(spell.level.data$cr == "yes") # Number of Spells with Civil Resistance Campaigns

sum(spell.level.data$cr == "yes" & spell.level.data$spell_outcome == "democracy protected")/sum(spell.level.data$cr == "yes") # Civil Resistance Success Rate

## Figure 1: Civil Resistance and Democratic Backsliding Outcomes ####

spell.level.data %>% 
  mutate(spell_outcome = factor(spell_outcome,levels = c("democracy protected","democracy preserved but deteriorated","authoritarian regime"),labels = c("Democracy\nProtcted","Democracy Preserved\nBut Deteriorated","Authoritarian\nRegime"))) %>% 
  ggplot(aes(spell_outcome,fill = cr)) + 
  geom_bar(position = "dodge") +
  scale_fill_manual(name = "Civil Resistance\nCampaign",values = c(theme.blue,theme.green)) +
  scale_y_continuous(breaks = c(0,2,4,6,8,10)) +
  labs(x = "",y = "Number of Spells") +
  theme_bw() +
  theme(text = element_text(size= 24),
        axis.text = element_text(size = 22)
  )

ggsave("figures/campaign_presence.png",width = 13,height = 8,dpi = 800)

## Table 1: Modeling Civil Resistance and Democratic Backsliding ####

democracy.mod <- glm(end.dem ~ cr + med.free + prez + dem.strt + rcsn,
                     data = spell.level.data,
                     family = binomial(link = "logit"))

clustered.mod <- coeftest(democracy.mod, # Cluster standard errors
         vcov = vcovCL,
         type = "HC1",
         cluster = ~country)

htmlreg(democracy.mod,
          custom.coef.map = list("cryes" = "Civil Resistance",
                                 "med.free" = "Media Freedom",
                                 "prez" = "Presidentialism",
                                 "dem.strt" = "Starting Democracy",
                                 "rcsn" = "Recession",
                                 "(Intercept)" = "Constant"),
          override.se = clustered.mod[,2], # Replace standard errors with clustered SEs
          override.pvalues = clustered.mod[,4], # Replace p-values with clustered p-values
        file = "figures/cr-dem-mod.doc")

## Marginal Effects of Civil Resistance ####

predictions(democracy.mod,newdata = datagrid(cr = c("no","yes"), 
                                             rcsn = 1, # Modal value of recession
                                             med.free = mean(spell.level.data$med.free),
                                             prez = mean(spell.level.data$prez),
                                             dem.strt = mean(spell.level.data$dem.strt)))

# What Strategies Have Shifted Pillar of Support Loyalty? ####

sum(loyalty.shift.data$alignment_shift,na.rm = T) # Number of Loyalty Shifts

table(loyalty.shift.data$alignment_shift,loyalty.shift.data$pillar) # Loyalty Shifts by Pillar

## Figure 2: Success Rates for Pillar Loyalty Shift Strategies ####

loyalty.data.final %>% 
  filter(cr == "yes") %>% 
  group_by(cr_tactic_main) %>% 
  summarize(success_perc = mean(alignment_shift,na.rm = T), count = n()) %>% 
  filter(!(is.na(cr_tactic_main))) %>% 
  mutate(cr_tactic_main = factor(cr_tactic_main,levels = c("bridgebuilding","none observed","protest (verbal)","protest (physical)"))) %>% 
  ggplot(aes(x = cr_tactic_main,y = success_perc)) +
  geom_col(fill = theme.blue) +
  geom_text(aes(label = scales::percent(success_perc)),vjust = -0.5,size = 8) +
  scale_y_continuous(labels = scales::percent,limits = c(0,0.5)) +
  scale_x_discrete(labels = c("Outreach","None Observed","Protest (Physical)","Protest (Verbal)")) +
  labs(x = "Primary Campaign Strategy",y = "Percentage Loyalty Shift") +
  theme_minimal() +
  theme(plot.background = element_rect(fill = "transparent",color = "transparent"),
        panel.background = element_rect(fill = "transparent", color = "transparent"),
        panel.grid = element_line(color = "gray70"),
        text = element_text(size= 24),
        axis.text = element_text(size = 22))

ggsave("figures/pillar_outreach.png",width = 13,height = 8,dpi = 800)

## Figure 3: Outreach Strategies and Predicted Pillar Loyalty ####

linear.defections.mod <- lm(align_end_num ~ outreach*align_begin_num + pillar,
                            data = loyalty.shift.data) 

alignment.scale.labels <- c("Completely Support\nRegime","Mostly Support\nRegime","Neutral\nOr Mixed","Mostly Support\nDemocracy","Completely Support\nDemocracy")


dfx.pred.plot <- plot_predictions(linear.defections.mod,
                                  by = c("align_begin_num","outreach"),
                                  vcov = ~case_id)

dfx.pred.plot +
  scale_color_manual(name = "Outreach",
                     labels = c("No","Yes"),
                     values = c(theme.blue,theme.green)) +
  scale_fill_manual(name = "Outreach",
                    labels = c("No","Yes"),
                    values = c(theme.blue,theme.green)) +
  scale_x_continuous(name = "Beginning Alignment",
                     breaks = 1:5,
                     labels = alignment.scale.labels) +
  scale_y_continuous(name = "Ending Alignment",
                     breaks = 1:5,
                     labels = alignment.scale.labels) +
  theme_bw() +
  theme(panel.grid.minor = element_blank(),
        text = element_text(size= 24),
        axis.text = element_text(size = 20),
        axis.text.x = element_text(angle = 45,hjust = 1))

ggsave("figures/outreach_predicted.png",width = 13,height = 8,dpi = 800)

# What tactics have pillars used to push back against democratic backsliding? ####

# Success rates by tactic

tactic.level.data %>% 
  group_by(tactic_category) %>% 
  summarize(success.rate = mean(success))

## Figure 4: Tactic Counts and Success Rates by Pillar ####

tactic.level.data %>% 
  mutate(success = if_else(tactic_outcome %in% c("significant success","modest success"),1,0)) %>% 
  group_by(pillar) %>% 
  summarize(tactics = n(),
            success.rate = mean(success,na.rm = T) %>% scales::percent()) %>% 
  mutate(pillar = c("Business","Civic","Faith","Veterans\nSecurity")) %>% 
  ggplot(aes(x = reorder(pillar,desc(tactics)),y = tactics)) + 
  geom_col(fill = theme.blue) +
  geom_text(aes(label = paste0(tactics,"\n (",success.rate," success)")),vjust = -0.5,size = 7) +
  scale_y_continuous(limits = c(0,230)) +
  labs(x = "",y = "Number of Tactics") +
  theme_bw() +
  theme(text = element_text(size= 24),
        axis.text = element_text(size = 20))

ggsave("figures/tactics_freq.png",width = 10,height = 8, dpi = 800)

## Figure 5: Predicted Success Across Non-Cooperation and Pillar ####

tactic.success.mod <- glm(success ~ noncooperation*pillar + 
                          v2x_polyarchy + v2cademmob +
                          country_name + as.factor(start_year),
                          family = binomial(link = "logit"), 
                          data = tactic.level.data) 

tactic.success.preds <- predictions(tactic.success.mod,
                                    by = c("noncooperation","pillar"),
                                    vcov = ~case_id)

ggplot(tactic.success.preds,aes(x = noncooperation,
                                y = estimate,
                                ymin = conf.low,
                                ymax = conf.high)) +
  geom_point() +
  geom_errorbar(width = 0.1) +
  scale_y_continuous(name = "Probability of Success",
                     labels = scales::percent) +
  scale_x_discrete(name = "Noncooperation Tactics") +
  facet_wrap(. ~ pillar,labeller = label_value) +
  theme_bw() +
  theme(panel.grid.minor = element_blank(),
        text = element_text(size= 24),
        axis.text = element_text(size = 20))

ggsave("figures/noncoop-success.png",width = 13,height = 8,dpi = 800)

